#include "EchoServer.hpp"
#include "BusinessService.hpp"
#include <iostream>

using std::cout;
using std::endl;

EchoServer::EchoServer(unsigned short port,const string & ip,int threadNum,int queSize)
:_threadpool(threadNum,queSize)
,_tcpServer(port)
{
    using namespace std::placeholders;
    _tcpServer.setAllCallbacks(
                std::bind(&EchoServer::onConnection,this,_1),
                std::bind(&EchoServer::onMessage,this,_1),
                std::bind(&EchoServer::onClose,this,_1) );
}

void EchoServer::start(){
    _threadpool.start();
    _tcpServer.start();
}

void EchoServer::stop(){
    _tcpServer.stop();
    _threadpool.stop();
}

void EchoServer::onConnection(TcpConnectionPtr conn){
    cout << "== Reactor V5 ==" << endl;
    cout << "IO thread " << pthread_self() << "——"
         << conn->toString() << " has connected successfully!" << endl;
}
    
void EchoServer::onMessage(TcpConnectionPtr conn){
    string msg = conn->receive();
    
    cout << "== Reactor V5 ==" << endl;
    cout << "IO thread recv msg : " << msg << endl;

    MyTask task(msg,conn);
    _threadpool.addTask(std::bind(&MyTask::process,task));
}

void EchoServer::onClose(TcpConnectionPtr conn){
    cout << "== Rector V5 ==" << endl;
    cout << "IO thread" << pthread_self() << "——"
         << conn->toString() << " has closed." << endl;
}
